<template>
  <div class="add-good">
    <el-form ref="addGoodForm" :model="addGoodForm" :rules="addGoodRules" label-position="top">
      <!-- 产品图片、产品名、产品价格、产品秒杀价、产品总量、产品描述、开始时间、结束时间 -->
      <div class="upload-image">
        <el-form-item label="产品图片" prop="good_img">
          <el-upload class="image-uploade" :action="uploadUrl" :show-file-list="false" :on-success="handleUploadSuccess"
            :before-upload="handleBeforeUpload" :headers="headers" :on-error="handleUploadError" name="file">
            <img v-loading="uploadLoading" v-if="addGoodForm.good_img" :src="addGoodForm.good_img" class="image" />
            <i v-else class="el-icon-plus image-uploade-icon"></i>
          </el-upload>
        </el-form-item>
      </div>

      <div class="add-good-title">
        <el-form-item label="产品名" prop="good_title">
          <el-input type="text" maxlength="10" placeholder="请输入产品名" v-model="addGoodForm.good_title" />
        </el-form-item>
      </div>

      <div class="add-good-desc">
        <el-form-item label="产品描述" prop="good_desc">
          <el-input type="textarea" maxlength="100" placeholder="请输入产品描述(小于100字)" v-model="addGoodForm.good_desc"
            show-word-limit />
        </el-form-item>
      </div>

      <div class="add-good-is-seckill">
        <el-form-item label="是否开启秒杀" prop="is_seckill">
          <el-select v-model="addGoodForm.is_seckill">
            <el-option label="否" value="0"></el-option>
            <el-option label="是" value="1"></el-option>
          </el-select>
        </el-form-item>
      </div>

      <div class="add-good-is-delivery">
        <el-form-item label="是否需要快递" prop="is_delivery">
          <el-select v-model="addGoodForm.is_delivery">
            <el-option label="否" value="0"></el-option>
            <el-option label="是" value="1"></el-option>
          </el-select>
        </el-form-item>
      </div>

      <div class="add-good-prices">
        <el-form-item label="产品价格" prop="price">
          <el-input type="text" placeholder="请输入产品价格" v-model="addGoodForm.price" />
        </el-form-item>
      </div>

      <div class="add-good-seckill-prices" v-if="addGoodForm.is_seckill === '1'">
        <el-form-item label="秒杀价格" prop="seckill_price">
          <el-input type="text" placeholder="请输入秒杀价格" v-model="addGoodForm.seckill_price" />
        </el-form-item>
      </div>

      <div class="add-good-total">
        <el-form-item label="产品总量" prop="total">
          <el-input type="text" placeholder="请输入产品总量" v-model="addGoodForm.total" />
        </el-form-item>
      </div>

      <div class="add-start-time" v-if="addGoodForm.is_seckill === '1'">
        <el-form-item label="开始时间" prop="start_time">
          <el-col :span="11">
            <el-date-picker type="date" placeholder="选择日期" v-model="addGoodForm.start_time"
              style="width: 100%"></el-date-picker>
          </el-col>
          <el-col :span="11" style="margin-left: 5%">
            <el-time-picker placeholder="选择时间" v-model="addGoodForm.start_time" style="width: 100%"></el-time-picker>
          </el-col>
        </el-form-item>
      </div>

      <div class="add-end-time" v-if="addGoodForm.is_seckill === '1'">
        <el-form-item label="结束时间" prop="end_time">
          <el-col :span="11">
            <el-date-picker type="date" placeholder="选择日期" v-model="addGoodForm.end_time"
              style="width: 100%"></el-date-picker>
          </el-col>
          <el-col :span="11" style="margin-left: 5%">
            <el-time-picker placeholder="选择时间" v-model="addGoodForm.end_time" style="width: 100%"></el-time-picker>
          </el-col>
        </el-form-item>
      </div>

      <div class="opera-btn">
        <div class="add-button">
          <el-button type="primary" :loading="addGoodLoading" @click="addGood('addGoodForm')">
            <span v-if="!addGoodLoading">添 加</span>
            <span v-else>添 加 中...</span>
          </el-button>
        </div>

        <div class="reset-button">
          <el-button @click="resetForm('addGoodForm')">重置</el-button>
        </div>
      </div>

    </el-form>
  </div>
</template>

<script>
import { insertGood } from "@/api/good";
import { getToken } from "@/utils/auth";
export default {
  name: "AddGood",
  data() {
    return {
      addGoodLoading: false,
      addGoodForm: {
        good_img: "",
        good_title: "",
        is_seckill: "0",
        is_delivery: "0",
        price: "",
        seckill_price: "",
        total: "",
        good_desc: "",
        start_time: "",
        end_time: "",
      },

      addGoodRules: {
        // good_img: [
        //   {
        //     required: true,
        //     message: "图片不能为空",
        //     trigger: "blur",
        //   },
        // ],
        good_title: [
          {
            required: true,
            message: "产品名不能为空",
            trigger: "blur",
          },
        ],
        price: [
          {
            required: true,
            message: '产品价格不能为空',
            trigger: "blur",
          },
        ],
        seckill_price: [
          {
            required: true,
            message: '产品秒杀价不能为空',
            trigger: "blur",
          },
        ],
        total: [
          {
            required: true,
            message: '产品总量不能为空',
            trigger: "blur",
          },
        ],
        start_time: [
          {
            required: true,
            message: "请输入开始时间不能为空",
            trigger: "blur",
          },
        ],
        end_time: [
          {
            required: true,
            message: "请输入结束时间不能为空",
            trigger: "blur",
          },
        ],
      },

      uploadLoading: false,

      uploadUrl: "/api/file/upload",
      headers: {
        tokenAuthorization: "Bearer" + getToken(),
      },
    };
  },

  methods: {
    handleImageSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },

    beforeImageUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },

    addGood(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.addGoodForm.is_seckill === '1' && isNaN(this.addGoodForm.seckill_price)) {
            this.$message.error('产品秒杀价只能是数字')
            return false
          }

          if (this.addGoodForm.is_seckill === '1') {

            let startDate = new Date(this.addGoodForm.start_time)
            let endDate = new Date(this.addGoodForm.end_time)

            if (startDate >= endDate) {
              this.$message.error('开始时间必须在结束日期前')
              return false
            }
          }

          if (isNaN(this.addGoodForm.price)) {
            this.$message.error('产品价格只能是数字')
            return false
          }

          if (isNaN(this.addGoodForm.total)) {
            this.$message.error('产品总量只能是数字')
            return false
          }

          this.addGoodLoading = true;

          insertGood(this.addGoodForm)
            .then(() => {
              this.$message.success("添加成功!");
              this.addGoodLoading = false;
              this.$refs[formName].resetFields();
            })
            .catch(() => {
              this.addGoodLoading = false;
            });
        } else {
          this.addGoodLoading = false;
          return false;
        }
      });
    },

    resetForm(formName) {
      this.$refs[formName].resetFields();
    },

    handleUploadSuccess(res) {
      this.$message.success("上传成功！");
      this.addGoodForm.good_img = res.data.url;
      this.uploadLoading = false;
    },

    handleBeforeUpload(file) {
      let fileExtension = "";
      if (file.name.lastIndexOf(".") > -1) {
        fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
      }

      if (
        fileExtension != "jpg" &&
        fileExtension != "png" &&
        fileExtension != "jpeg"
      ) {
        this.$message.error("上传图片格式不符");
        return false;
      }

      const fileSize = file.size / 1024 / 1024 < 5;
      if (!fileSize) {
        this.$message.error("上传图片大小不能超过 5MB！");
        return false;
      }

      this.uploadLoading = true;
    },

    handleUploadError() {
      this.$message.error("上传失败，请稍后重试");
      this.uploadLoading = false;
    },
  },
};
</script>

<style>
.image-uploade .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  margin-left: 30px;
  margin-top: 10px;
}

.image-uploade .el-upload:hover {
  border-color: #409eff;
}

.image-uploade-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.image {
  width: 200px;
  height: 100px;
  display: block;
}

.el-form-item__label {
  padding-bottom: 0px !important;
}

.opera-btn {
  display: flex;
  justify-content: center;
  gap: 20px;
}

.add-button .el-button,
.reset-button .el-button {
  width: 150px;
  height: 40px;
}
</style>